package com.hc.pingtan.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hc.pingtan.model.CommonResult;
import com.hc.pingtan.model.SxoPluginsCoupon;
import com.hc.pingtan.model.SxoPluginsCouponUser;
import com.hc.pingtan.model.SxoUser;
import com.hc.pingtan.service.ISxoPluginsCouponService;
import com.hc.pingtan.service.ISxoPluginsCouponUserService;
import com.hc.pingtan.service.ISxoUserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 用户优惠券 - 应用 前端控制器
 * </p>
 *
 * @author astupidcoder
 * @since 2021-11-03
 */
@RestController
@RequestMapping("/sxo-plugins-coupon-user")
public class SxoPluginsCouponUserController {

    @Autowired
    private ISxoUserService mISxoUserService;
    @Autowired
    private ISxoPluginsCouponUserService mISxoPluginsCouponUserService;
    @Autowired
    private ISxoPluginsCouponService mISxoPluginsCouponService;

    /**
     * 领取优惠券
     *
     * @return
     */
    @ApiImplicitParams({@ApiImplicitParam(name = "uId", value = "用户名称（必填）"), @ApiImplicitParam(name = "couponId", value = "优惠券ID必填")})
    @ApiOperation(value = "领取优惠券", notes = "领取优惠券", httpMethod = "GET")
    @GetMapping("/getDiscount")
    public CommonResult getDiscount(String uId, Integer couponId) {
        CommonResult result = CommonResult.builder().build();
        if (StringUtils.isNotBlank(uId)) {
            //获取用户信息
            QueryWrapper<SxoUser> wrappersUser = new QueryWrapper();
            wrappersUser.eq("username", uId);
            SxoUser one = mISxoUserService.getOne(wrappersUser);
            if (one == null) {
                result.setResult("帐号错误");
                return result;
            }
            SxoPluginsCoupon coupon = mISxoPluginsCouponService.getById(couponId);
            SxoPluginsCouponUser user = new SxoPluginsCouponUser();
            user.setIsUse(false);
            user.setAddTime((int)DateUtil.currentSeconds());
            user.setIsValid(false);
            user.setUserId(one.getId());
            user.setTimeEnd(coupon.getExpireHour() * 60 * 60 + ((int)DateUtil.currentSeconds()));
            user.setCouponId(couponId);
            user.setTimeStart((int)DateUtil.currentSeconds());
            user.setUpdTime((int)DateUtil.currentSeconds());
            user.setUserId(one.getId());
            mISxoPluginsCouponUserService.save(user);
        }
        return CommonResult.builder().build();

    }

}
